<template>
	<div class="zh-registration-import">
		<nav-header>
			<template slot="menuBefore">
                <li><router-link to="/life/dormitory/accommodation-registration" tag="a">住宿登记</router-link></li>
				<li class="gap">&gt;</li>
			</template>
            <li @click="goBack" style="cursor: pointer">{{roomTitle}}</li>
            <li class="gap" v-if="roomTitle2">&gt;</li>
			<li @click="goBack2" style="cursor: pointer">{{roomTitle2}}</li>
            <li class="gap">&gt;</li>
            <li>批量导入</li>
		</nav-header>
        
		<div class="zh-import-comter">
				<el-button plain @click="downloadDemo">下载模板</el-button>
			    <uploader 
                    :options="uploadOptions" 
                    :autoStart="false" 
                    ref="uploader" 
                    :file-status-text="statusText" 
                    @files-submitted="fileSubmit"
                    @file-removed="fileRemoved" 
                    @file-success="fileSuccess" 
                    @file-error="fileFail"  
                    class="uploader-example">
				    <uploader-unsupport></uploader-unsupport>
				    <uploader-btn :directory="false" :attrs="attrs" v-if="selectFileShow" :single="true">选择文件</uploader-btn>
				    <uploader-list  v-if="!selectFileShow"></uploader-list>
				</uploader>
				<el-button type="primary" v-if="!selectFileShow" @click="fileUpload" style="margin-top: 10px;">确定导入</el-button>
		</div>
		<div class="zh-import-text">
			<p>注意事项: </p>
			<p>1、Excel从数据表中第二行开始有效。</p>
			<p>2、表头为红色字体的为必填项，黑色字体的为选填项。</p>
			<p>3、入住时间格式按照2019-01-01导入，否则将导入失败。 </p>
			<p>4、每个寝室的床位限制最高为20个床位，超出部分无法导入。</p>
			<p>5、小学班级填写格式为：X年级（X）班；初中&高中班级填写格式为：初X（X）班。</p>
			<p>6、填写时请勿删除“填写须知”和“示例”。</p>
			<p>7、请确保账号填写正确，系统将会根据账号数据自动带出学生姓名、学号、班级和班主任。</p>
		</div>
		<div class="zh-import-table">
			<p>例：</p>
			<div class="zh-table">
				<div class="zh-table-contents">
                    <el-table
                        :data="importData"
                        border
                        fixed
                        style="width: 100%">
                        <el-table-column
                            prop="0"
                            label="序号"
                            align="center"
                            width="50px"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="1"
                            label="寝室号"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="2"
                            label="床位"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="3"
                            label="账号"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="4"
                            label="姓名"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="5"
                            label="学号"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="6"
                            label="班级"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="7"
                            label="班主任"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="8"
                            label="入住时间"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                    </el-table>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
    import {downloadBatchDemo, uploaderFileFail, longTimeMessage} from './../../../tools/tool';

	export default {
	    data() {
		    return {
                roomTitle: '', // 寝室地址
                roomTitle2: '', // 寝室地址
                buildingId: null, // 宿舍楼 id
		    	messageObj:{},
		    	statusText: {
			      	success: '上传成功',  
			      	error: '上传出错',  
			     	uploading: '正在上传...',  
			      	paused: '暂停',  
			      	waiting: '等待上传'  
				},
				selectFileOrNot:false,  //是否选中文件
			    uploadOrNot:false, 		//是否已经上传
			    uploadInfo:{
					file_name:'',
					file_path:'',
					file_size:0
				},
				attrs: {
			      	accept: ['application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
			    },
		    	uploadOptions: {
			          target: this.BASE_URL+'/api/dormitory/vue_demo_upload',
			          testChunks: false,
			          headers:{Authorization : `Bearer `+this.$g.access_token},
			    },
		        fileList: [],
	      		selectFileShow:true,//是否显示选择文件按钮
				uploadRetryTimes:100,//文件最大重传次数
				importData: [
                    {
                        0: '1',
                        1: '101',
                        2: '1',
                        3: 'zhangxiaowei',
                        4: '张小伟',
                        5: '20191015',
                        6: '一年级（2）班',
                        7: '李娜',
                        8: '2019-08-25',
                    }
                ],
                excelUploader: null, // 上传组件引用
	      	}
        },
        created() {
            this.getRoomInfo();
        },
        mounted () {
            this.$nextTick(() => {  
                this.excelUploader = this.$refs.uploader.uploader  
            })  
		},
	    methods: {
            goBack() {
                sessionStorage.setItem('ldarId', this.buildingId);
                this.$router.push('/life/dormitory/accommodation-registration');
            },
            goBack2() {
                this.$router.push('/life/dormitory/registration-detail/' + this.$route.params.id);
            },
            /**
            * 获取寝室信息
            */
            getRoomInfo() {
                let success = (res => {
                    this.roomTitle = res.data.building_name;
                    this.roomTitle2 = res.data.number;
                    this.buildingId = res.data.building_id;
                })

                this.$ajax.get('api/dormitory/dormitory',{params: {id: this.$route.params.id}, func:{success: success}});
            },
            /**
             * 下载导出模板
             */
	    	downloadDemo(){
                let url = this.BASE_URL+'/index/resource/user_dormitory_import_demo';
                downloadBatchDemo(url);
	    	},
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if( this.selectFileOrNot ){
							this.fileUpload();
						}else{
							this.resourceSave();
						}
					} else {
						return false;
					}
				});
			},
	        resourceSave(){
				let resourceParam = {};
				if( this.uploadOrNot ) {
					resourceParam.path = this.uploadInfo.file_path;
				}
                resourceParam.building_id = this.$route.params.id;
                
            	let success = ( data=>{
            		this.$message.success(data.msg);
                    
                    setTimeout(() => {
                        this.$router.go(-1);
                    }, 1000);
            	})
            	let fail = (res => {
                    longTimeMessage(this, res, 15000);
            	}) 
            	
				this.$ajax.post('api/dormitory/dormitoryUserImport', resourceParam, {func:{success:success, fail:fail}})	
			},
			//上传成功的事件  
			fileSuccess (rootFile, file, message, chunk) { 
				this.selectFileShow = true;
                var mess = eval('(' + message + ')');
                mess = handleResponseData( mess );
                
			 	if(parseInt( mess.data.status ) ===1 ){
			  		this.uploadOrNot = true;
			  		this.uploadInfo.file_name = mess.data.file_name;
			  		this.uploadInfo.file_path = mess.data.file_path;
			  		this.uploadInfo.post_fix = mess.data.post_fix;
			  	
			  		this.resourceSave();
                }
                this.excelUploader.removeFile(file);
			},
			fileFail(rootFile, file, message, chunk) {
                uploaderFileFail(this, this.excelUploader, file, message);
			},
			//过滤文件格式
			fileSubmit(files, fileList, event){
				for (var i = 0 ; i < fileList.length ; i++ ) {
                    if( this.excelUploader.fileList.length  > 1  ){
                        //删除第一张图片
                        this.excelUploader.removeFile( this.excelUploader.fileList[0] );
                    }
                    this.uploadInfo.file_size = fileList[i].size;
                    this.selectFileOrNot = true;
                    this.selectFileShow = false;
				}
			},
			fileRemoved(file){
				this.selectFileOrNot = false;
				this.selectFileShow = true;
			},
			fileUpload(){
				this.excelUploader.upload();
			},
			back(n){
				this.$router.go(n);	
			},
	    },
		destroyed(to, from, next) {
			this.$message.closeAll();
		},
	}
</script>
<style lang="scss">
	.zh-registration-import {
		.zh-import-comter {
			margin-top: 20px;
		}
		.uploader-example {
			margin-top: 20px;
		}
		.zh-import-text {
			font-size: 12px;
		    color: #999;
		    line-height: 30px;
		    margin: 20px;
		    p {
		    	margin: 0;
		    }
		    span {
			    color: red;
			}
		}
		.zh-import-table {
			p {
				font-size: 16px;
				margin-bottom: 20px;
			}
		}
		.uploader-list {
		    .uploader-file-pause {
		      display: none !important;
		    }
		    .uploader-file-status {
		      text-indent: 0;
		    }
 		}

        .el-table__header-wrapper table thead {
            tr:last-child {
                th:nth-child(2),
                th:nth-child(3),
                th:nth-child(4),
                th:nth-child(9) {
                    color: red;
                }
            }
        }
	}
</style>